//
//  HomeEconomicsListViewController.m
//  cityStar
//
//  Created by joyban on 15-1-20.
//  Copyright (c) 2015年 tiny. All rights reserved.
//

#import "HomeEconomicsListViewController.h"
#import "SingleTableView.h"
#import "HomeEconomicsListCell.h"
#import "HomeEconomicDetailViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "selectDistrict.h"

#import "SVPullToRefresh.h"
#import "HomeModel.h"
#import "HomemakingViewController.h"
#import "HomemakingNeedViewController.h"
#import "RIButtonItem.h"
#import "UIActionSheet+Blocks.h"
#import "LoginCityStarViewViewController.h"
#import "BaseNavController.h"
NSString *const HomeEconomicsListCellID = @"HomeEconomicsListCellID";

@interface HomeEconomicsListViewController ()<SingleTableViewDelegate,CLLocationManagerDelegate>

@property (retain, nonatomic) CLLocationManager *locManager;
@property (nonatomic, assign) CLLocationCoordinate2D loc;


@property (weak, nonatomic) IBOutlet UITableView *HomeEconomicsTable;
@property (weak, nonatomic) IBOutlet UIButton *selectBtn;
@property (weak, nonatomic) IBOutlet UIButton *typebtn;

@property (nonatomic, weak) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIImageView *typeImageView;
@property (strong, nonatomic) SingleTableView *typeSingleTableView;

@property (nonatomic, weak) IBOutlet UIImageView *selectImageView;
@property (strong, nonatomic) SingleTableView *selectSingleTableView;

@property (nonatomic, assign) BOOL isShowAddressList;
@property(nonatomic,strong) NSMutableArray *cityArr;
@property(nonatomic,strong) NSArray *areaArr;
@property(nonatomic,strong) NSArray *currentAreaArr;
@property (nonatomic, assign) int page;
@property (nonatomic, strong) NSMutableArray *arrayRequest;
@property (nonatomic, weak) IBOutlet UILabel *nothinglabel;
@property (nonatomic, assign) NSString *strOrder;
@property (nonatomic, assign) NSString *strDistrict;
@property (nonatomic, assign) NSString *strDistrictid;

@end

@implementation HomeEconomicsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"家政服务";
    [self addBackButton];
    [self setUpTableViews];
    __weak typeof(self)weakSelf = self;
    
    [self addRightButtonWithTitle:@"    发布" actionBlock:^{
        if (weakSelf.currentUser.nickname) {
        RIButtonItem *cancelItem = [RIButtonItem itemWithLabel:@"取消"];
        
        RIButtonItem *giveServierItem = [RIButtonItem itemWithLabel:@"提供服务" action:^{
            HomemakingViewController *homemakingPublishVC = [[HomemakingViewController alloc]init];
            [weakSelf.navigationController pushViewController:homemakingPublishVC animated:YES];
        }];
        RIButtonItem *needServierItem = [RIButtonItem itemWithLabel:@"需要服务" action:^{
            HomemakingNeedViewController *homemakingneedPublishVC = [[HomemakingNeedViewController alloc]init];
            [weakSelf.navigationController pushViewController:homemakingneedPublishVC animated:YES];
        }];
        UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"选择服务类型" cancelButtonItem:cancelItem destructiveButtonItem:giveServierItem otherButtonItems:needServierItem, nil];
        [actionSheet showInView:weakSelf.view];
        }else{
            [weakSelf presentLoginViewController];
        }
    }];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAddressStatues) name:@"isShowAddressList" object:nil];
    
    self.strOrder = @"";
    self.strDistrict = @"";
    self.locManager = [[CLLocationManager alloc]init];
    //设置代理
    self.locManager.delegate = self;
    //设置位置经度
    self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
    //设置每隔100米更新位置
    self.locManager.distanceFilter = 100;
    //开始定位服务
    [self.locManager startUpdatingLocation];
    
    self.cityArr = [[NSMutableArray alloc]init];
    [self.cityArr addObject:@"全部区域"];
    self.arrayRequest = [[NSMutableArray alloc]init];
    
    [self.HomeEconomicsTable addPullToRefreshWithActionHandler:^{
        self.page = 1;
        [weakSelf webRequest_GetHomeEconomMore:NO];
        
    }];
    [self.HomeEconomicsTable addInfiniteScrollingWithActionHandler:^{
        [weakSelf webRequest_GetHomeEconomMore:YES];
        
    }];
    [self.HomeEconomicsTable triggerPullToRefresh];
}

- (void)webRequest_GetHomeEconomMore:(BOOL)isMore
{
    NSString *EndUrl = @"";
    NSString *postUrl = [NSString stringWithFormat:@"%@/type/%d/page/%d/mine/%d",KInterface_PublishList,5,isMore?self.page:0,0];
    EndUrl = postUrl;
    if(![self.strDistrict isEqualToString:@""])
    {
        EndUrl = [NSString stringWithFormat:@"%@/district/%@",EndUrl,self.strDistrictid];
    }
    if(![self.strOrder isEqualToString:@""])
    {
        NSString *strid = @"";
        if([self.strOrder isEqualToString:@"家政保洁"])
        {
            strid = @"1";
        }else if([self.strOrder isEqualToString:@"公司保洁"]){
            strid = @"2";
        }
        else{
            strid = @"3";
        }
        EndUrl = [NSString stringWithFormat:@"%@/service_type/%@",EndUrl,strid];
    }
    [HttpRequestManager getMethod:[EndUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            if (isMore) {
                [self.arrayRequest addObjectsFromArray:response[@"value"][0][@"content"]];
                self.page = self.page + 1;
            }else{
                self.arrayRequest = [[NSMutableArray alloc]initWithArray:response[@"value"][0][@"content"]];
            }
            [self.HomeEconomicsTable reloadData];
            if (self.arrayRequest.count == 0) {
                self.nothinglabel.hidden = NO;
            }else{
                self.nothinglabel.hidden = YES;
            }
        }
        if (isMore) {
            [self.HomeEconomicsTable.infiniteScrollingView stopAnimating];
        }else{
            [self.HomeEconomicsTable.pullToRefreshView stopAnimating];
        }
    }];
}

#pragma mark - locationDelegate
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

//协议中的方法，作用是每当位置发生更新时会调用的委托方法
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    //结构体，存储位置坐标
    self.loc = [newLocation coordinate];
    //    CLLocation *currentLocation = [INTULocationManager sharedInstance].currentLocation;
    
    NSString *postUrl  = [NSString stringWithFormat:@"%@%f/%f",KInterFace_location,self.loc.latitude,self.loc.longitude];
    [HttpRequestManager getMethod:postUrl parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            NSString *str = response[@"value"][@"detail"][@"city_code"];
            [self webRequest_citydataWithCityID:str];
        }else{
            
        }
    }];
}

-(void)webRequest_citydataWithCityID:(NSString *)sendeid
{
    NSString *getPul = [NSString stringWithFormat:@"%@/%@",KInterface_getRegion,sendeid];
    [HttpRequestManager getMethod:getPul parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            [[selectDistrict shardDistrictInfo]setClasscityArray:response[@"value"]];
            
            self.cityArr = [[NSMutableArray alloc]init];
            NSArray *array = [[NSArray alloc]init];
            array = [selectDistrict shardDistrictInfo].DistrictArray;
            
            [self.cityArr addObject:@"选择区域"];
            [array enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                [self.cityArr addObject:obj[@"name"]];
            }];
        }else{
            DLog(@"%@",errMsg);
            [SVProgressHUD showErrorWithStatus:errMsg];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setUpTableViews
{
    [self.HomeEconomicsTable registerNib:[HomeEconomicsListCell nib] forCellReuseIdentifier:HomeEconomicsListCellID];
}

#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [HomeEconomicsListCell heightOfTableCell];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayRequest.count;
}

#pragma mark - UITableViewDataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeEconomicsListCell *homeEconomicsListCell = [tableView dequeueReusableCellWithIdentifier:HomeEconomicsListCellID];
    HomeArrayModel *model = [HomeArrayModel objectFromDictionary:self.arrayRequest[indexPath.row]];
    [homeEconomicsListCell setDataHomeModel:model];
    homeEconomicsListCell.selectionStyle = UITableViewCellSelectionStyleGray;
    return homeEconomicsListCell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeEconomicDetailViewController *homeEconomicdetailViewController = [[HomeEconomicDetailViewController alloc]init];
    HomeArrayModel *model = [HomeArrayModel objectFromDictionary:self.arrayRequest[indexPath.row]];
    homeEconomicdetailViewController.homeModel = model;
    homeEconomicdetailViewController.hidesBottomBarWhenPushed = YES;
    homeEconomicdetailViewController.withchType = @"cityService";
    [self.navigationController pushViewController:homeEconomicdetailViewController animated:YES];
    [tableView reloadData];
}



-(void)changeAddressStatues
{
    self.isShowAddressList = NO;
}

#pragma mark - Actions
-(IBAction)allTypes_atction:(id)sender
{
    if(self.typebtn.selected == NO)
    {
        self.typebtn.selected = YES;
    }else{
        self.typebtn.selected = NO;
    }
    self.selectBtn.selected = NO;
    
    [self.typeSingleTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    self.typeSingleTableView.dataArray = @[@"全部类型",@"家政保洁",@"公司保洁",@"钟点工"];
}

-(IBAction)select_atction:(id)sender
{
    if(self.selectBtn.selected == NO)
    {
        self.selectBtn.selected = YES;
    }else
    {
        self.selectBtn.selected = NO;
    }
    self.typebtn.selected = NO;
    
    [self.selectSingleTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    self.selectSingleTableView.dataArray =self.cityArr;
}

#pragma mark - singleTableViewDelegate
-(SingleTableView *)typeSingleTableView
{
    if (!_typeSingleTableView) {
        _typeSingleTableView = [[SingleTableView alloc] init];
        _typeSingleTableView.delegate = self;
        [self addChildViewController:_typeSingleTableView];
        [self.view addSubview:_typeSingleTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _typeSingleTableView.arrawImageView = self.typeImageView;
    }
    return _typeSingleTableView;
}

-(void)singleTableView:(SingleTableView *)tableView didSelectedCellAtIndexPath:(NSIndexPath *)indexPath
{
    self.typebtn.selected = NO;
    self.selectBtn.selected = NO;
    if (tableView == self.typeSingleTableView) {
        NSString *celltest = @[@"全部类型",@"家政保洁",@"公司保洁",@"钟点工"][indexPath.row];
        self.strOrder = celltest;
        if([self.strOrder isEqualToString:@"全部类型"])
        {
            self.strOrder = @"";
        }
        if (celltest.length > 4) {
            NSString *btnTitle = [NSString stringWithFormat:@"%@..",[celltest substringWithRange:NSMakeRange(0, 4)]];
            [self.typebtn setTitle:btnTitle forState:UIControlStateNormal];
        }else{
            [self.typebtn setTitle:celltest forState:UIControlStateNormal];
            
        }
    }else{
        NSString *celltest = self.cityArr[indexPath.row];
        self.strDistrict = self.cityArr[indexPath.row];
        NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[selectDistrict shardDistrictInfo].DistrictIdArray];
        [array addObject:@""];
        if([self.strDistrict isEqualToString:@"选择区域"] == YES)
        {
            self.strDistrict = @"";
        }else{
            NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[selectDistrict shardDistrictInfo].DistrictIdArray];
            [array addObject:@""];
            self.strDistrictid = array[indexPath.row-1];
        }
        if (celltest.length > 4) {
            NSString *btnTitle = [NSString stringWithFormat:@"%@..",[celltest substringWithRange:NSMakeRange(0, 4)]];
            [self.selectBtn setTitle:btnTitle forState:UIControlStateNormal];
        }else{
            [self.selectBtn setTitle:celltest forState:UIControlStateNormal];
        }
    }
    self.page = 1;
    [self webRequest_GetHomeEconomMore:NO];
}

-(void)cancleTabelView
{
    self.typebtn.selected = NO;
    self.selectBtn.selected = NO;
}

-(SingleTableView *)selectSingleTableView
{
    if (!_selectSingleTableView) {
        _selectSingleTableView = [[SingleTableView alloc] init];
        _selectSingleTableView.delegate = self;
        [self addChildViewController:_selectSingleTableView];
        [self.view addSubview:_selectSingleTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _selectSingleTableView.arrawImageView = self.selectImageView;
    }
    return _selectSingleTableView;
}
#pragma mark - reset button size

//-(void)resetItemSizeBy:(NSString*)str{
//    //    [self.btnAddress setTitleColor:[UIColor colorWithWhite:0.580 alpha:1.000] forState:UIControlStateNormal];
//    if (str.length >= 5) {
//        NSString *btnTitle = [NSString stringWithFormat:@"%@..",[str substringWithRange:NSMakeRange(0, 4)]];
//        ;
//        [self.selectBtn setTitle:btnTitle forState:UIControlStateNormal];
//    }else{
//        [self.selectBtn setTitle:str forState:UIControlStateNormal];
//    }
//}


#pragma mark - FSDropDown datasource & delegate

//- (NSInteger)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
//    if (tableView == menu.rightTableView) {
//        return _cityArr.count;
//    }else{
//        return _currentAreaArr.count;
//    }
//}
//- (NSString *)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView titleForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (tableView == menu.rightTableView) {
//        
//        return _cityArr[indexPath.row];
//    }else{
//        return _currentAreaArr[indexPath.row];
//    }
//}
//
//- (void)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    if(tableView == menu.rightTableView){
//        _currentAreaArr = _areaArr[indexPath.row];
//        [menu.leftTableView reloadData];
//    }else{
//        self.isShowAddressList = NO;
//        self.selectBtn.selected = NO;
//        self.typebtn.selected = NO;
//        [self resetItemSizeBy:_currentAreaArr[indexPath.row]];
//    }
//}

-(void)senderCancle
{
    self.selectBtn.selected = NO;
    self.typebtn.selected = NO;
}

#pragma mark - IsJumpToLoginViewController
-(void)presentLoginViewController
{
    LoginCityStarViewViewController *loginCityStarVC = [[LoginCityStarViewViewController alloc]init];
    BaseNavController *baseloginNav = [[BaseNavController alloc] initWithRootViewController:loginCityStarVC];
    [self presentViewController:baseloginNav animated:YES completion:^{
    }];
}


@end
